const express = require('express');
const mysql = require('mysql');

const app = express()

app.use(express.json())

app.all('*', (req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*')
    res.header('Access-Control-Allow-Headers', 'Content-Type')

    if (res.methods === 'OPTIONS') {
        res.sendStatusCode(200)
    } else {
        next()
    }

})



// -- 创建数据库
// CREATE DATABASE blog;

// -- 使用数据库
// USE blog;

// -- 创建用户信息表
// CREATE TABLE users (
//     id INT AUTO_INCREMENT PRIMARY KEY,
//     username VARCHAR(255) NOT NULL,
//     password VARCHAR(255) NOT NULL,
//     name VARCHAR(255) NOT NULL,
//     contact VARCHAR(255),
//     purpose TEXT,
//     role VARCHAR(255) NOT NULL
// );


app.post('/users', (req, res) => {
    const { username, password, name, contact, role } = req.data;

    const sql1 = ` select * from users where username = + ${username} `
    db.query(sql1, (err, rows) => {
        if (err) {
            console.error('Error inserting data:', err);
            res.status(500).send('DB error');
        }
        else if (rows.length == 0) {
            const sql2 = `select * from users where username = + ${username} +  and password =  + ${password}`
            db.query(sql2, (err, rows) => {
                if (rows.lenght > 0) {
                    res.status(200).send('登录成功')
                }
            })
        }
        else {
            res.status(400).send('账号出错')
        }
    })




    const sql = 'INSERT INTO users (username, password, name, contact, purpose, role) VALUES (?, ?, ?, ?, ?, ?)';
    const values = [username, password, name, contact, JSON.stringify(purpose), role];

    db.query(sql, values, (err, results) => {
        if (err) {
            console.error('Error inserting data:', err);
            res.status(500).send('Server error');
        } else {
            res.status(200).send('User data saved successfully');
        }
    });

})



app.listen(5362, () => {
    console.log('server listening on 5362')
})


